from datetime import datetime

from rest_framework.views import exception_handler
from rest_framework import status

from users.models import UserInfo


def status_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    # 状态码
    if response is not None:
        # 需要先获取
        response.data['code'] = response.status_code
        response.status_code = status.HTTP_200_OK
        try:
            response.data['message'] = exc.detail
            response.data.pop('detail')
        except:
            print(response.data)
            response.data['message'] = response.data.pop('detail', '字段不存在')
        response.data['data'] = {}

    return response


def jwt_response_payload_handler(token, user=None, request=None):
    current = UserInfo.objects.get(username=user)
    current.last_login = datetime.now()
    current.save()
    return {
        'code': 200,
        'message': 'success',
        'data': {
            'token': token,
            'user_id': user.id,
            'username': user.username
        }
    }
